package com.essence.common.http;

import cn.hutool.json.JSONUtil;
import okhttp3.*;

import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.Objects;

public class HttpClient {
    public synchronized static Response uploadFiles(String url, File... files) {
        try {
            OkHttpClient client = new OkHttpClient();
            MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
            for (File f : files) {
                builder.addFormDataPart("files", f.getName(),
                        RequestBody.create(f, MediaType.parse("multipart/form-data")));
            }

            RequestBody requestBody = builder.build();
            Request req = new Request.Builder()
                    .url(url)
                    .post(requestBody)
                    .build();

            Response resp = client.newCall(req).execute();
            if (resp.isSuccessful()) {
                return resp;
            }
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    public synchronized static Response get(String url, Map<String, String> params) {
        try {
            OkHttpClient client = new OkHttpClient();
            HttpUrl.Builder urlBuilder = Objects.requireNonNull(HttpUrl.parse(url)).newBuilder();
            if (params != null) {
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    urlBuilder.addQueryParameter(entry.getKey(), entry.getValue());
                }
            }
            Request request = new Request.Builder()
                    .url(urlBuilder.build().toString())
                    .get()
                    .build();
            Response resp = client.newCall(request).execute();
            if (resp.isSuccessful()) {
                return resp;
            }
            return null;
        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        }
    }

    public synchronized static byte[] downloadGet(String url, Map<String, String> params) {
        OkHttpClient client = new OkHttpClient();
        HttpUrl.Builder urlBuilder = Objects.requireNonNull(HttpUrl.parse(url)).newBuilder();
        if (params != null) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                urlBuilder.addQueryParameter(entry.getKey(), entry.getValue());
            }
        }
        Request request = new Request.Builder()
                .url(urlBuilder.build().toString())
                .get()
                .build();
        try {
            Response resp = client.newCall(request).execute();
            return Objects.requireNonNull(resp.body()).bytes();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return null;
    }
}
